﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using nyxwin.Common.Base.Utils;
using nyxwin.Common.Settings;
using nyxwin.Data.Session;

namespace nyxwin.Main
{
    public partial class StartupPage : PhoneApplicationPage
    {
        public StartupPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var authorizationNick = ApplicationSettings.Instance.AuthorizationNick;
            var authorizationToken = ApplicationSettings.Instance.AuthorizationToken;
            var authorizationCode = ApplicationSettings.Instance.AuthorizationCode;

            if (string.IsNullOrEmpty(authorizationNick) || string.IsNullOrEmpty(authorizationToken))
            {
                NavigationService.Navigate(new Uri("/View/LoginPage.xaml", UriKind.Relative));
            }
            else
            {
                #region MailPeriodicTask
                PeriodicTask mailCheckPeriodicTask = ScheduledActionService.Find(Constants.MailCheckPeriodicTaskName) as PeriodicTask;
                if (mailCheckPeriodicTask != null)
                {
                    try
                    {
                        ScheduledActionService.Remove(Constants.MailCheckPeriodicTaskName);
                    }
                    catch
                    {
                        /* Ignore this one */
                    }
                }

                mailCheckPeriodicTask = new PeriodicTask(Constants.MailCheckPeriodicTaskName);
                mailCheckPeriodicTask.Description = Constants.MailCheckPeriodicTaskDescription;
                mailCheckPeriodicTask.ExpirationTime = DateTime.Now.AddDays(1);

                try
                {
                    ScheduledActionService.Add(mailCheckPeriodicTask);

#if DEBUG
                    ScheduledActionService.LaunchForTest(Constants.MailCheckPeriodicTaskName, TimeSpan.FromSeconds(30D));
#endif
                }
                catch
                {
                    /* TODO: ISOTOXIN: Log exception or warn user if agents are disabled for some reason */
                }
                #endregion

                // Reset count at start
                var shellTile = ShellTile.ActiveTiles.FirstOrDefault();
                if (shellTile != null)
                {
                    shellTile.Update(new StandardTileData() { Count = 0 });
                }

                new LoginManager().IsAuthorized(authorizationNick, authorizationToken,
                    (evArgs) =>
                    {
                        if (evArgs.AuthorizationStatus == "AUTH_NEW") // requested new credz
                        {
                            ApplicationSettings.Instance.AuthorizationNick = authorizationNick;
                            ApplicationSettings.Instance.AuthorizationToken = authorizationToken = evArgs.AuthorizationToken;
                            ApplicationSettings.Instance.AuthorizationCode = authorizationCode = evArgs.AuthorizationCode;

                            Dispatcher.BeginInvoke(() => MessageBox.Show(string.Format("Your new authorization code is: {0}", authorizationCode), "Important !", MessageBoxButton.OK));
                        }

                        Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/View/MainPage.xaml", UriKind.Relative)));
                    }
                );
            }

            base.OnNavigatedTo(e);
        }
    }
}